<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: Core.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Vote_Api_Core extends Core_Api_Abstract {
	
	public function createMusicParticipant($file, $params = array()) {
		if (is_array ( $file )) {
			if (! is_uploaded_file ( $file ['tmp_name'] )) {
				throw new Exception ( 'Invalid upload or file too large 1.' . print_r ( $file, true ) );
			}
			$filename = $file ['name'];
		} else if (is_string ( $file )) {
			$filename = $file;
		} else {
			throw new Exception ( 'Invalid upload or file too large 2.' );
		}
		
		// Check file extension
		if (! preg_match ( '/\.(mp3|m4a|aac|mp4)$/iu', $filename )) {
			throw new Exception ( 'Invalid file type 3.' );
		}
		
		// upload to storage system
		$params = array_merge ( array ('type' => 'vote_challenge', 'name' => $filename, 'parent_type' => 'vote_challenge', 'parent_id' => Engine_Api::_ ()->user ()->getViewer ()->getIdentity (), 'user_id' => Engine_Api::_ ()->user ()->getViewer ()->getIdentity (), 'extension' => substr ( $filename, strrpos ( $filename, '.' ) + 1 ) ), $params );
		
		$song = Engine_Api::_ ()->storage ()->create ( $file, $params );
		
		return $song;
	}
	
	public function createVideoParticipant($params, $file) {
		if ($file instanceof Storage_Model_File) {
			$params ['file_id'] = $file->getIdentity ();
		} else {
			// create video item
			$participant = Engine_Api::_ ()->getDbtable ( 'participants', 'vote' )->createRow ();
			$file_ext = pathinfo ( $file ['name'] );
			$file_ext = $file_ext ['extension'];
			$participant->code = $file_ext;
			$participant->user_id = $params ['owner_id'];
			$participant->save ();
			
			// Store video in temp directory for ffmpeg to handle
			$tmp_file = APPLICATION_PATH . '/temporary/vote_participant/' . $participant->getIdentity () . "." . $file_ext;
			$tmp_path = dirname ( $tmp_file );
			
			if (! file_exists ( $tmp_path )) {
				mkdir ( $tmp_path, 0777, true );
			}
			
			$src_fh = fopen ( $file ['tmp_name'], 'r' );
			$tmp_fh = fopen ( $tmp_file, 'w' );
			stream_copy_to_stream ( $src_fh, $tmp_fh );
			
			Engine_Api::_ ()->getDbtable ( 'jobs', 'core' )->addJob ( 'participant_encode', array ('participant_id' => $participant->getIdentity () ) );
		}
		
		return $participant;
	}
	
	public function getTags($params = array()) {
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$db = $table->getAdapter ();
		$select = $db->select ();
		
		$prefix = $table->getTablePrefix ();
		
		$select->from ( $prefix . 'core_tagmaps', array ('tag_id', 'challenge_id' => $prefix . 'core_tagmaps.resource_id', 'freq' => 'COUNT(' . $prefix . 'core_tagmaps.tag_id)' ) )->joinLeft ( $prefix . 'core_tags', $prefix . 'core_tagmaps.tag_id = ' . $prefix . 'core_tags.tag_id', array ('text' ) )->joinLeft ( $prefix . 'vote_challenges', $prefix . 'core_tagmaps.resource_id = ' . $prefix . 'vote_challenges.challenge_id', array () )->where ( $prefix . "core_tagmaps.resource_type = 'vote_challenge'" )->where ( $prefix . "vote_challenges.approved = 1" )->group ( $prefix . 'core_tags.text' );
		
		if (! empty ( $params ['challenge_id'] )) {
			if (is_array ( $params ['challenge_id'] )) {
				$where = $prefix . "core_tagmaps.resource_id IN (" . implode ( ',', $params ['challenge_id'] ) . ")";
			} elseif (is_numeric ( $params ['challenge_id'] )) {
				$where = $prefix . "core_tagmaps.resource_id = {$params['challenge_id']}";
			}
			$select->where ( $where );
		}
		
		if (! empty ( $params ['type'] )) {
			$select->where ( $prefix . 'vote_challenges.type = ?', $params ['type'] );
		}
		
		if (! empty ( $params ['period'] )) {
			if ($params ['period'] == 'past') {
				$select->where ( $prefix . 'vote_challenges.endtime < FROM_UNIXTIME(?)', time () );
			} elseif ($params ['period'] == 'upcoming') {
				$time = time ();
				$select->where ( $prefix . 'vote_challenges.starttime > FROM_UNIXTIME(?)', $time );
			} elseif ($params ['period'] == 'active') {
				$time = time ();
				$select->where ( $prefix . 'vote_challenges.endtime > FROM_UNIXTIME(?) AND ' . $prefix . 'vote_challenges.starttime < FROM_UNIXTIME(?)', $time, $time );
			}
		}
		
		$rawData = $db->fetchAll ( $select ); // he_pa($rawData); exit();
		$type = '';
		
		if (! empty ( $params ['categorized'] )) {
			$type = $params ['categorized'];
		}
		
		return $this->categorizeTags ( $rawData, $type );
	}
	
	public function categorizeTags($rawData, $type = '') {
		$tags = array ();
		if ($type == 'vote_challenge') {
			foreach ( $rawData as $item ) {
				$tags [$item ['vote_challenge']] [] = $this->defineTagClass ( $item );
			}
		} else {
			foreach ( $rawData as $item ) {
				$tags [] = $this->defineTagClass ( $item );
			}
		}
		
		return $tags;
	}
	
	public function defineTagClass($tag) {
		if (empty ( $tag ['freq'] )) {
			return $tag;
		}
		
		if ($tag ['freq'] <= 1) {
			$tag ['class'] = 1;
		} elseif ($tag ['freq'] <= 3) {
			$tag ['class'] = 2;
		} elseif ($tag ['freq'] <= 7) {
			$tag ['class'] = 3;
		} elseif ($tag ['freq'] <= 10) {
			$tag ['class'] = 4;
		} elseif ($tag ['freq'] <= 20) {
			$tag ['class'] = 5;
		} elseif ($tag ['freq'] <= 40) {
			$tag ['class'] = 6;
		} elseif ($tag ['freq'] <= 65) {
			$tag ['class'] = 7;
		} elseif ($tag ['freq'] <= 100) {
			$tag ['class'] = 8;
		} else {
			$tag ['class'] = 9;
		}
		
		return $tag;
	}
	
	public function isAllowedCreation($user = null) {
		if (! $user) {
			$user = Engine_Api::_ ()->user ()->getViewer ();
		}
		
		if (! ($user instanceof User_Model_User)) {
			return false;
		}
		
		$max = Engine_Api::_ ()->getDbTable ( 'permissions', 'authorization' )->getAllowed ( 'vote_challenge', $user, 'max' );
		$voteCount = $this->getUserVotingCount ( $user );
		
		if ($voteCount > $max) {
			return false;
		}
		
		if (! Engine_Api::_ ()->authorization ()->isAllowed ( 'vote_challenge', $user, 'create' )) {
			return false;
		}
		
		return true;
	}
	
	public function getUserVotingCount($user) {
		if (! $user) {
			$user = Engine_Api::_ ()->user ()->getViewer ();
		}
		
		if (! ($user instanceof User_Model_User)) {
			return false;
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$name = $table->info ( 'name' );
		$select = $table->select ()->setIntegrityCheck ( false )->from ( $name, array ('cnt' => 'COUNT(challenge_id)' ) )->where ( 'user_id = ?', $user->getIdentity () )->group ( 'user_id' );
		
		return ( int ) $table->getAdapter ()->fetchOne ( $select );
	}
	
	public function checkSlug($voting = null, $slug = '') {
		if (! $slug) {
			return false;
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$name = $table->info ( 'name' );
		$select = $table->select ()->setIntegrityCheck ( false )->from ( $name, array ('challenge_id' ) )->where ( 'slug = ?', $slug );
		
		if (! $voting && Engine_Api::_ ()->core ()->hasSubject ()) {
			$subject = Engine_Api::_ ()->core ()->getSubject ();
			if ($subject->getType () == 'vote_challenge') {
				$voting = $subject;
			}
		}
		
		if ($voting instanceof Vote_Model_Challenge) {
			$select->where ( 'challenge_id <> ?', $voting->getIdentity () );
		}
		
		$row = $table->fetchRow ( $select );
		
		return ( bool ) $row;
	}
	
	public function getCategories($type = '') {
		$table = Engine_Api::_ ()->getDbTable ( 'categories', 'vote' );
		$select = $table->select ();
		
		if ($type) {
			$select->where ( 'type = ?', $type );
		}
		
		return $table->fetchAll ( $select );
	}
	
	public function getCategoryOptions($type = '') {
		$table = Engine_Api::_ ()->getDbTable ( 'categories', 'vote' );
		$name = $table->info ( 'name' );
		
		$select = $table->select ()->setIntegrityCheck ( false )->from ( $name, array ('category_id', 'category_name' ) );
		
		if ($type) {
			$select->where ( 'type = ?', $type );
		}
		
		return $table->getAdapter ()->fetchPairs ( $select );
	}

}